package com.authsphere.security.token.redis.configuration;

import com.authsphere.security.token.common.AuthenticationTokenServices;
import com.authsphere.security.token.common.TokenStore;
import com.authsphere.security.token.redis.RedisTokenServices;
import com.authsphere.security.token.redis.RedisTokenStore;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;

/**
 * @program: AuthSphere
 * @description:
 * @author: YuKai Fan
 * @create: 2025/3/25 15:03
 **/
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class TokenRedisConfiguration {

    @Bean
    @ConditionalOnBean(RedisConnectionFactory.class)
    public TokenStore redisTokenStore(final RedisConnectionFactory connectionFactory) {
        return new RedisTokenStore(connectionFactory);
    }

    @Bean
    @ConditionalOnBean(TokenStore.class)
    public AuthenticationTokenServices redisTokenServices(final TokenStore tokenStore, final ObjectProvider<AccessTokenConfig> provider) {
        RedisTokenServices redisTokenServices = new RedisTokenServices(provider.getIfAvailable(AccessTokenConfig::new));
        redisTokenServices.setTokenStore(tokenStore);
        return redisTokenServices;
    }

    @Bean
    @ConfigurationProperties(prefix = "authsphere.security.token.redis")
    public AccessTokenConfig accessTokenConfig() {
        return new AccessTokenConfig();
    }
}
